package cn.edu.sdjzu.xg.eagle.dao;

import cn.edu.sdjzu.xg.eagle.entity.Department;
import cn.edu.sdjzu.xg.eagle.entity.School;
import cn.edu.sdjzu.xg.eagle.util.JdbcHelper;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DepartmentDaoImpl implements DepartmentDaoInterface {
    static private DepartmentDaoInterface departmentDaoImpl = null;
    public DepartmentDaoImpl(){}

    public static DepartmentDaoInterface getInstance(){
        if (departmentDaoImpl == null) {
            departmentDaoImpl = new DepartmentDaoImpl();
            System.out.println("Create DepartmentDaoImpl Object");
        }
        return departmentDaoImpl;
    }
    @Override
    public Department find(Long id) throws SQLException {
        String sql = "SELECT * FROM department WHERE id = ?";
        Department department = null;

        try (Connection conn = JdbcHelper.getConn();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setLong(1, id);

            try (ResultSet rs = pstmt.executeQuery()) {
                if (rs.next()) {
                    String description = rs.getString("description");
                    String no = rs.getString("department_no");
                    String remarks = rs.getString("remarks");
                    Long schoolId = rs.getLong("school_id");

                    School school = SchoolDaoImpl.getInstance().find(schoolId);
                    department = new Department(id, description, no, remarks, school);
                }
            }
        }
        return department;
    }

    @Override
    public void add(Department department) throws SQLException {
    }

    @Override
    public boolean update(Connection connection, Department department) throws SQLException {
        String sql = "UPDATE department SET description=?, no=?, remarks=?, school_id=? WHERE id=?";

        try (PreparedStatement pstmt = connection.prepareStatement(sql)) {
            pstmt.setString(1, department.getDescription());
            pstmt.setString(2, department.getNo());
            pstmt.setString(3, department.getRemarks());
            pstmt.setLong(4, department.getSchool().getId());
            pstmt.setLong(5, department.getId());

            int rows = pstmt.executeUpdate();
            return rows > 0;
        }
    }

    @Override
    public boolean delete(Long id) throws SQLException {
        String sql = "DELETE FROM department WHERE id=?";

        try (Connection conn = JdbcHelper.getConn();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setLong(1, id);
            int rows = pstmt.executeUpdate();
            return rows > 0;
        }
    }

    @Override
    public  boolean delete(Department department) throws SQLException {
        return delete(department.getId());
    }
}
